package com.huxiu;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.huxiu.net.GsonRequest;
import com.huxiu.net.NetworkConstants;
import com.huxiu.net.NetworkHelper;
import com.huxiu.net.responses.BaseResponse;
import com.huxiu.utils.Constants;
import com.huxiu.utils.ErrorResponseException;
import com.huxiu.utils.TextViewUtil;
import com.huxiu.utils.UmenEvent;
import com.huxiu.utils.Utils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.umeng.analytics.MobclickAgent;

import java.util.LinkedHashMap;
import java.util.Map;


/**
 * Created by tian on 15/4/20:上午9:21.
 */
public class SubmitCommentActivity extends Activity implements OnClickListener {
    @ViewInject(R.id.content)
    protected View content;

    @ViewInject(R.id.background)
    protected View background;

    @ViewInject(R.id.submit_button)
    TextView submitButton;

    @ViewInject(R.id.text_exit)
    TextView text_exit;

    @ViewInject(R.id.edit)
    EditText edit;

    private String articleId;

    private String pid;

    private String typeArticle;

    private String replyname="";

    private String value;

    private String COMMENT_INTENT_VALUE="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        setContentView(R.layout.activity_submit_comment);
        ViewUtils.inject(this);
        articleId = getIntent().getStringExtra(Constants.ARTICLE_ID_KEY);
        if(getIntent().hasExtra(Constants.REPLYNAME)){
            replyname=getIntent().getStringExtra(Constants.REPLYNAME);
            value="@"+replyname+":";
        }
        edit.setText(value);
        edit.setSelection(edit.length());
        typeArticle = getIntent().getStringExtra("type_article");
        if (typeArticle.equals("add_postcomment")) {
            pid = getIntent().getStringExtra(Constants.COMMENT_ID_KEY);
        }
        if(getIntent().hasExtra(UmenEvent.COMMENT_INTENT_KEY)){
            COMMENT_INTENT_VALUE= getIntent().getStringExtra(UmenEvent.COMMENT_INTENT_KEY);
        }

        background.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_CANCEL
                        || event.getAction() == MotionEvent.ACTION_UP) {
                    if (TextUtils.isEmpty(edit.getText().toString())) {
                        background.requestFocus();
                        finish();
                    } else {
                        new Builder(SubmitCommentActivity.this).setTitle(R.string.content_not_empty)
                                .setPositiveButton(android.R.string.ok,
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                background.requestFocus();
                                                finish();
                                            }
                                        }).setNegativeButton(android.R.string.cancel, null).show();
                    }
                }
                return true;
            }
        });
        submitButton.setOnClickListener(this);
        text_exit.setOnClickListener(this);
        edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (typeArticle.equals("add_postcomment")) {
                    Log.e("str", "stuse" + TextViewUtil.isReplyEntity(value, s.toString()));
                    boolean status=TextViewUtil.isReplyEntity(value, s.toString());
                    submitButton.setEnabled(!status);
                }else{
                    submitButton.setEnabled(s != null && s.toString().trim().length() > 0);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {


            }
        });
        InputMethodManager imm = (InputMethodManager) edit.getContext().getSystemService(Context
                .INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);

        edit.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub
                if (s.length() >= 1){
                    submitButton.setTextColor(getResources().getColor(R.color.button_login));
                } else {
                    submitButton.setTextColor(getResources().getColor(R.color.gray4));
                }
                submitButton.setEnabled(s != null && s.length() > 0);
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.submit_button:
                if (TextUtils.isEmpty(edit.getText().toString().trim())) {
                    Utils.showToast("请输入评论内容");
                    return;
                }
                submitComment();
                break;
            case R.id.text_exit:
                finish();
                break;
        }
    }

    private void submitComment() {
        String url = (typeArticle.equals("add_post") ? NetworkConstants.ADD_POST : NetworkConstants
                .ADD_POSTCOMMENT);
        Map<String, String> params = new LinkedHashMap<>();
        String id = typeArticle.equals("add_post") ? "aid" : "pid";
        if (id.equals("aid")) {
            params.put("aid", articleId);
        } else if (id.equals("pid")) {
            params.put("pid", pid);
        }
        params.put("message", edit.getText().toString().trim());
        GsonRequest<BaseResponse> request = new GsonRequest<>(
                url,
                Method.POST, BaseResponse.class, true, params, new Response.Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response) {
                if (response.isSuccess()) {
                    Utils.showToast(R.string.submit_comment_success);
                    Intent intent = new Intent(Constants.INTENT_ARTICLE_COMMENT_SUCCESS);
                    LocalBroadcastManager.getInstance(APP.getInstance()).sendBroadcast(intent);
                    UmengEvent();
                    finish();
                } else {
                    Utils.showToast(response.error.message);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Throwable t = error.getCause();
                if (t instanceof ErrorResponseException) {
                    Utils.showToast(error.getMessage());
                } else {
                    Utils.showToast(R.string.generic_failure);
                }
            }
        });
        NetworkHelper.getInstance().addToRequestQueue(request);
//        mQueue.start();
    }


    @Override
    public void finish() {
        // TODO Auto-generated method stub
        super.finish();
        //关闭窗体动画显示
        this.overridePendingTransition(R.anim.activity_colse,0);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK ){
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("SplashScreen");
        MobclickAgent.onResume(this);
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("SplashScreen");
        MobclickAgent.onPause(this);
    }


    public void UmengEvent(){
        if(COMMENT_INTENT_VALUE.equals(UmenEvent.ARTICLE_DETAIL_SEND_COMMENT)){
            UmenEvent.UmengEventMap(this, UmenEvent.COMMENT_LIST, UmenEvent.ARTICLE_DETAIL_SEND_COMMENT);
        }else if(COMMENT_INTENT_VALUE.equals(UmenEvent.COMMENT_LISTBOTTOM_REPLY_COMMENT)){
            UmenEvent.UmengEventMap(this, UmenEvent.COMMENT_LIST, UmenEvent.COMMENT_LISTBOTTOM_REPLY_COMMENT);
        }else if(COMMENT_INTENT_VALUE.equals(UmenEvent.COMMENT_LISTREPLY_COMMENT)){
            UmenEvent.UmengEventMap(this, UmenEvent.COMMENT_LIST, UmenEvent.COMMENT_LISTREPLY_COMMENT);
        }
    }
}
